package com.hejia.alauda.utils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;


/**
 * @author John
 * Cookie 工具类
 */
public class CookieUtils {
	
	public static final ThreadLocal<Cookie> local = new ThreadLocal<>();
	
	/**
	 * 每次获取都会新建一个COOKIE
	 * */
	public static Cookie getCookie(String name,String value) {
		Cookie cookie = new Cookie(name,value);
		cookie.setPath("/");
		local.set(cookie);
		return cookie;
	}
	
	public static Cookie setMaxAge(int maxAge) {
		Cookie cookie = local.get();
		
		if (cookie == null) 
			throw new NullPointerException("cookie is null");
		
		if (maxAge > 0)
			cookie.setMaxAge(maxAge);
		
		return cookie;
	}
	
	public static Cookie setPath(String path) {
		Cookie cookie = local.get();
		
		if (cookie == null) 
			throw new NullPointerException("cookie is null");
		
		if (StringUtils.isEmpty(path))
			cookie.setPath("/");
		else 
			cookie.setPath(path);
		
		return cookie;
	}

	public static Cookie query(String name,HttpServletRequest request) {
		Cookie[] cookies = request.getCookies();
		
		if (StringUtils.isEmpty(name)) 
			throw new NullPointerException("cookie name is null");
		
		Cookie cookie = null;
		
		for (Cookie value : cookies) {
			if (name.equals(value.getName()))
				cookie = value;
		}
		
		return cookie;
	}
}
